from rest_framework import serializers

from PAA_ERP.utils.get_inventory import get_inventory
from goods_info.models import GoodsModel, GoodsInventoryModel, AttachmentModel
from goods_info.serializer.units_serializer import UnitsSerializers
from goods_info.serializer.category_serializer import CategorySerializers
from goods_info.serializer.attachment_serializer import AttachmentSerializers


class GoodsInventorySerializer(serializers.ModelSerializer):
    """
    商品的库存 序列化器
    """

    class Meta:
        model = GoodsInventoryModel
        fields = '__all__'


class GoodsBaseSerializer(serializers.ModelSerializer):
    """
    商品新增，修改，的序列化器
    """
    # 商品对应的多个：商品库存对象。因为有很多个仓库
    inventory_list = GoodsInventorySerializer(many=True, required=True)

    class Meta:
        model = GoodsModel
        fields = '__all__'

    def create(self, validated_data):
        # 该新增商品的，库存对象的列表
        item_list = validated_data.pop('inventory_list')
        # 插入（纯粹的）商品信息，才会自动的生成一个ID
        goods = GoodsModel.objects.create(**validated_data)
        for item in item_list:
            # 新建时当前库存=新建库存
            item['cur_inventory'] = item.get('init_inventory', 0)
            GoodsInventoryModel.objects.create(goods=goods, **item)
        return goods

    def update(self, instance, validated_data):
        # 该新增商品的，库存对象的列表
        item_list = validated_data.pop('inventory_list')
        for item in item_list:  # 遍历每条库存信息，并修改最高库存和最低库存
            GoodsInventoryModel.objects.filter(warehouse_name=item['warehouse_name']).update(
                lowest_inventory=item.get('lowest_inventory', 0), highest_inventory=item.get('highest_inventory', 0))
        goods = super(GoodsBaseSerializer, self).update(instance=instance, validated_data=validated_data)
        return goods


class GoodsGetSerializer(serializers.ModelSerializer):
    """
    商品查询的序列化器
    目标：
        1、把商品的单位——所有信息展示出来
        2、展示商品信息所属的商品列表——所有信息展示出来
        3、展示商品的所有附件图片——所有图片信息展示出来
        4、展示商品的所有仓库中的库存信息
    """

    units = UnitsSerializers(read_only=True)
    category = CategorySerializers(read_only=True)
    images_list = serializers.SerializerMethodField(read_only=True)
    inventory_list = GoodsInventorySerializer(many=True, read_only=True)
    # 该货品的当前总库存数量
    cur_inventory = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = GoodsModel
        fields = '__all__'

    def get_images_list(self, obj):
        result = []
        if obj.images_list:
            ids = obj.images_list.split(',')
            if ids:
                for i in ids:
                    try:
                        image_id = int(i)
                        image = AttachmentModel.objects.get(id=image_id)
                        ser = AttachmentSerializers(instance=image)
                        result.append(ser.data)
                    except ValueError:
                        # 处理无效的ID，比如输出错误信息或跳过该ID
                        print(f"Invalid ID: {i}")
        return result
    def get_cur_inventory(self, obj):
        return get_inventory(obj.id)